package main

import (
	"context"
	"encoding/json"

	"gofw-im/lib/define"
	pb "gofw-im/lib/grpc"
	"gofw-im/lib/logger"
	"gofw-im/lib/net"
	"gofw-im/lib/proto"

	"google.golang.org/grpc"
)

var (
	cometRpcClient pb.CometClient
)

func InitCometRpc() (err error) {
	_, addr, err := net.ParseNetwork(conf.CometConf.Addr)
	conn, err := grpc.Dial(addr, grpc.WithInsecure())
	if err != nil {
		logger.Error.Printf("connect err rpc comet: %s", err)
	}
	//defer conn.Close()
	cometRpcClient = pb.NewCometClient(conn)
	return
}

// PushSingleToComet 广播信息到单个用户
func PushSingleToComet(serverId int8, userId string, msg []byte) {
	_, err := cometRpcClient.PushMsg(context.Background(), &pb.PushMsgArg{
		Uid: userId,
		P:   &pb.Proto{Ver: 1, Operation: define.OP_SINGLE_SEND, Body: msg},
	})
	if err != nil {

	}
}

// 广播信息到房间
func broadcastRoomToComet(roomId int32, msg []byte) {
	_, _ = cometRpcClient.PushRoomMsg(context.Background(), &pb.RoomMsgArg{RoomId: roomId, P: &pb.Proto{Ver: 1, Operation: define.OP_ROOM_SEND, Body: msg}})
}

// 广播在线人数到房间
func broadcastRoomCountToComet(roomId int32, count int) {

	var (
		body []byte
		err  error
	)
	msg := &proto.RedisRoomCountMsg{
		Count: count,
		Op:    define.OP_ROOM_COUNT_SEND,
	}

	if body, err = json.Marshal(msg); err != nil {
		logger.Error.Printf("broadcastRoomCountToComet  json.Marshal err :%s", err)
		return
	}

	_, _ = cometRpcClient.PushRoomCount(context.Background(), &pb.RoomMsgArg{RoomId: roomId, P: &pb.Proto{Ver: 1, Operation: define.OP_ROOM_SEND, Body: body}})
}

/**
广播房间信息到房间
*/
func broadcastRoomInfoToComet(roomId int32, roomUserInfo map[string]string) {

	var (
		body []byte
		err  error
	)
	msg := &proto.RedisRoomInfo{
		Count:        len(roomUserInfo),
		Op:           define.OP_ROOM_COUNT_SEND,
		RoomUserInfo: roomUserInfo,
		RoomId:       roomId,
	}

	if body, err = json.Marshal(msg); err != nil {
		logger.Error.Printf("broadcastRoomInfoToComet  json.Marshal err :%s", err)
		return
	}

	pushMsgArg := &pb.RoomMsgArg{
		RoomId: roomId, P: &pb.Proto{
			Ver:       1,
			Operation: define.OP_ROOM_SEND,
			Body:      body,
		},
	}

	_, _ = cometRpcClient.PushRoomInfo(context.Background(), pushMsgArg)
}
